<script setup lang="ts">
import { onUnmounted } from 'vue'
import { useFileSelector } from '@st/hooks/useFileSelector'
import { ElMessage } from 'element-plus'

interface Props {
  templateName: string
  templateUrl?: string
  templateMethod?: (option: any) => Promise<any>
  templateMethodOpt?: Record<string, any>
}

const props = defineProps<Props>()

const handleTemplateDownload = () => {
  if (!props.templateUrl && !props.templateMethod) {
    ElMessage({
      type: 'error',
      message: '未提供完整的模板下载信息！'
    })
    return
  }
  if (props.templateUrl) {
    window.location.href = props.templateUrl
    return
  } else {
    props.templateMethod &&
      props.templateMethod(props.templateMethodOpt || {}).then((res: any) => {
        let blob = new Blob([res.data])
        let url = window.URL.createObjectURL(blob) // 创建 url 并指向 blob
        let a = document.createElement('a')
        a.href = url
        a.download = res.filename
        a.click()
        window.URL.revokeObjectURL(url)
      })
  }
}

const { selectedFile, selectedFileName, callOpen, removeFile } = useFileSelector()

const getSelectedFile = () => {
  return selectedFile.value
}

defineExpose({
  getSelectedFile
})

onUnmounted(() => {
  if (selectedFile.value) {
    removeFile()
  }
})
</script>

<template>
  <div class="business-import-box-wrapper">
    <el-button v-if="!selectedFileName" type="primary" @click="callOpen">选择文件</el-button>
    <el-tag v-if="selectedFileName" size="large" closable @close="removeFile">{{ selectedFileName }}</el-tag>
    <div class="download-templete-box" @click="handleTemplateDownload">
      <div class="download-label">模板下载：</div>
      <div class="download-link">{{ props.templateName }}</div>
    </div>
  </div>
</template>

<style lang="scss" scope>
.business-import-box-wrapper {
  .download-templete-box {
    display: flex;
    margin-top: 16px;
    .download-link {
      color: var(--theme-color);
      cursor: pointer;
    }
  }
}
</style>
